import java.awt.Point;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

 /* 
 * @author Alan Linker
 * @see PuzzleCell
 */

public class FileHandler{
	/**
	 * @param args
	 */
	private PuzzleBoard board;
	private final String CR = "\r";
	public FileHandler(PuzzleBoard theBoard)
	{
		board = theBoard;	
	}

	public void loadBoard(String filename, WordList wl) throws IOException
	{
	  String line;

	  int width = 0, height = 0;
	  int y;
	  int linesize;
	  char letter;
	  
	  FileReader fr = new FileReader(filename);
	  BufferedReader br = new BufferedReader(fr);
	  
	  //read header
	  line = br.readLine(); //*board x y *

	  String[] parts = line.split("[ ]"); //parse header
	  //verify header
	  if (parts.length == 4)
		  if (parts[0].equals("*board")) {
			  width = Integer.parseInt(parts[1]);
			  height = Integer.parseInt(parts[2]);
		  }
	  if (width == 0 || height == 0)
		  throw new IOException("Invalid puzzleboard header in: " + filename);
	  
	  board.setDimensions(width, height);
	  board.clear();
	  y = 0;
	  while((line = br.readLine()) != null) {
		  linesize = line.length();
		  if (y < height) { //read puzzleboard
			  if (linesize != width)
				  throw new IOException("Invalid puzzleboard width in: " + filename);
			  for (int x=0; x < width; x++) {
				  letter = line.charAt(x);
				  if (Character.isLetter(letter))
					  board.setChar(x, y, letter);
				  else
					  throw new IOException("Invalid puzzleboard character in: " + filename);
			  }
	  	  }
		  else if(y == height) { //read wordlist header
			  wl.clear();
			  if (!line.equals("*wordlist*"))
				  throw new IOException("Wordlist header missing in: " + filename);
		  }
		  else { //read wordlist & letter positions in format "word|x1 y1|x2 y2|x3 y3|x4 y4"
			  parts = line.split("[|]"); //delimiter between points
              Point[] location = new Point[parts[0].length()];
			  if (parts.length > 1) {
				  //XXXXX not checking to see if word length matches # of positions  
				  for (int i = 1; i <= parts[0].length(); i++) { //get each letter position
					  String[] pos = parts[i].split("[ ]");
					  int a = Integer.parseInt(pos[0]); //X
					  int b = Integer.parseInt(pos[1]); //Y
					  location[i-1] = new Point(a, b);
				  }
				  try{
					  wl.addWord(parts[0], location);
					  System.out.println("** addword: '" + parts[0] + "' array size" + parts.length); //XXXXX
				  }
				  catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			  }
			  else
				  throw new IOException("Wordlist word (" + parts[0] + ")in improper format in: " + filename);
		  }
		  y++;
	  }
      //XXXXXX finally block
	  br.close();
	  fr.close();
	}
	public void saveBoard(String filename, WordList wordlist) throws IOException
	{
		// saves the board in .PUZ format
		int width = board.getWidth();
		int height = board.getHeight();
		String line = "*board ";
		String[] words;   //words array from the wordlist
		Point[] location; //the position of each letter in a word
		FileWriter outputStream = new FileWriter(filename);

		line += width + " " + height + " *" + CR;
		outputStream.write(line); //header:  *board x y*
        // save the board
		for (int y = 0; y < height; y++) {
			line = "";
		   for (int x = 0; x < width; x++) {
		      line += board.getChar(x, y);
		   }
		   outputStream.write(line + "" + CR);
	    }
	   
	   // save the word list
	   outputStream.write("*wordlist*" + CR);
	   words = wordlist.getWords(); //returns an array of strings
	   for (int i = 0; i < words.length; i++) {
	      line = words[i];
          location = wordlist.getLocation(words[i]);
	      for (int p = 0; p < location.length; p++) {
	         line += "|" + (int) location[p].getX() + " " + (int) location[p].getY();
	      }
	      outputStream.write(line + CR);
	   }
		outputStream.close();
	}

	public void saveHTML(String filename, WordList wl) throws IOException
	{  //save the board as an HTML file
		int width = board.getWidth();
		int height = board.getHeight();
		
		FileWriter outputStream = new FileWriter(filename);
		
		outputStream.write("<html>" + CR);
		outputStream.write("<head>" + CR);
		outputStream.write("<center>");
		outputStream.write("<title>iWare's Word Search Puzzle</title>" + CR);
		outputStream.write("<h2>Word Search by iWare</h2>" + CR);
		outputStream.write("</header>" + CR);
		outputStream.write("<font size=\"16\" face=\"Verdana\">" + CR);

		outputStream.write("<STYLE TYPE=\"text/css\">");
		outputStream.write("<!--TD{font-family: Arial; font-size: 20pt;}--->");
		outputStream.write("</STYLE>" + CR);

		outputStream.write("<table border=\"0\" WIDTH=180 CELLPADDING=0>" + CR);
		for (int y=0; y< height; y++)
		{
			outputStream.write("<tr>"); //start row
				for (int x=0; x< width; x++)
				{
					outputStream.write("<td>"); //cell (column)
					outputStream.write(board.getChar(x, y));
					outputStream.write("</td>"); //end cell
				}
			outputStream.write("</tr>" + CR); //finish row
		}
		outputStream.write("</table>" + CR + "<p><p>");
		//print word list
		String[] words = wl.getWords(); //returns an array of strings
		for (int i = 0; i < words.length; i++)
		{
			outputStream.write(words[i] + "<br />" + CR);
		}
		outputStream.write("</html>" + CR);
		outputStream.close();

	}

	public void saveWSFormat(String filename) throws IOException
	{
		// saves the board in .PUZ format
		int width = board.getWidth();
		int height = board.getHeight();
		String line;
		String[] words;
		Point[] location;
		FileWriter outputStream = new FileWriter(filename);

		line = height + " " + width;
		outputStream.write(line); //header:  *board y x*
        // save the board
		for (int y = 0; y < height; y++)
		{
			line = "";
		   for (int x = 0; x < width; x++)
		   {
		      line += board.getChar(x, y);
		   }
		   outputStream.write(line);
	   }
		outputStream.close();
	}
	public void loadWordList(String filename, WordList wl) throws IOException
	{ // loads a word list from a standard text file
		String word;
		
		FileReader fr = new FileReader(filename);
		BufferedReader br = new BufferedReader(fr);
		  
		while((word = br.readLine()) != null)
		{
			try{
				wl.addWord(word);
                System.out.println("word: " + word);
			}
			catch(Exception e){
                throw new IOException("Wordlist word in improper format in: " + filename);
			}
		}

	}
	public void printPuzzle()
	{
	}


}
